<script lang="ts" setup>
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import dayjs from 'dayjs'
import { GetSentcouponData } from '@/api/modules/signintask'
import GetCacheData from '@/store/modules/NewPageCache'

// const imgDomain = 'https://img1.eprhan.cc'
const cacheData = GetCacheData()

let PageNum = cacheData.GetCacheData('signintaskSentcoupon').currentPage
const loading = ref(true)
const total = ref(0)

const findFrom = ref({
  ...(cacheData.GetCacheData('signintaskSentcoupon').fromData),
})
const dataList: any = reactive({
  list: [],
})

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.OpenId && ({ OpenId: findFrom.value.OpenId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.TicketId && ({ TicketId: findFrom.value.TicketId })),
    ...(findFrom.value.Title && ({ Title: findFrom.value.Title })),
    ...(findFrom.value.SignDays && ({ SignDays: findFrom.value.SignDays })),
  }
  await GetSentcouponData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}

async function ExportExcel() {
  const params = {
    PageIndex: 1,
    PageSize: 5000,
    ...(findFrom.value.OpenId && ({ OpenId: findFrom.value.OpenId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.TicketId && ({ TicketId: findFrom.value.TicketId })),
    ...(findFrom.value.Title && ({ Title: findFrom.value.Title })),
    ...(findFrom.value.SignDays && ({ SignDays: findFrom.value.SignDays })),
  }

  const excelData = await GetSentcouponData(params)

  const headerMapping = {
    id: '发券记录ID',
    userId: '用户ID',
    scOpenId: '用户OpenId',
    userNickName: '用户昵称',
    userPhone: '授权手机号',
    taskId: '任务ID',
    title: '任务标题',
    cycleStart: '签到开始日期',
    signDays: '连续签到天数',
    couponId: '券ID',
    couponName: '券名称',
    couponType: '券类型',
    addTime: '添加时间',
    updateTime: '修改时间',
  } as { [key: string]: string }

  // 映射数据和合并order对象
  const newData = excelData.data.items.map((item: { [key: string]: any }) => {
    // 解构用户信息
    item.userId = item.subscriber?.userId
    item.scOpenId = item.subscriber?.scOpenId
    item.userNickName = item.subscriber?.userNickName
    item.userPhone = item.subscriber?.userPhone

    delete item.subscriber

    // 解构券信息
    item.couponId = item.couponInfo?.id
    item.couponName = item.couponInfo?.name
    item.couponType = item.couponInfo?.type

    delete item.couponInfo

    return Object.keys(item).reduce((newItem, key) => {
      (newItem as { [key: string]: any })[headerMapping[key] || key] = item[key]
      return newItem
    }, {})
  })
  // console.log(newData)

  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(newData)
  // 设置列宽
  ws['!cols'] = [{ wch: 10 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 30 }, { wch: 20 }, { wch: 20 }, { wch: 15 }, { wch: 15 }, { wch: 30 }]
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, `发券记录_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`)
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('signintaskSentcoupon').currentSize)
  cacheData.SetCacheData('signintaskSentcoupon', PageNum, cacheData.GetCacheData('signintaskSentcoupon').currentSize, findFrom.value)
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('signintaskSentcoupon', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('signintaskSentcoupon').currentSize)
  cacheData.SetCacheData('signintaskSentcoupon', val, cacheData.GetCacheData('signintaskSentcoupon').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('signintaskSentcoupon').currentPage || 1
})

onMounted(async () => {
  GetDataList(PageNum, cacheData.GetCacheData('signintaskSentcoupon').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="被邀请人OpenId">
                <el-input v-model="findFrom.OpenId" placeholder="请输入被邀请人OpenId" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入邀请人用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="券ID">
                <el-input v-model="findFrom.TicketId" placeholder="请输入券ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="任务标题">
                <el-input v-model="findFrom.Title" placeholder="请输入任务标题" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="连续签到天数">
                <el-input v-model="findFrom.SignDays" placeholder="请输入连续签到天数" clearable @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="发券记录ID" width="100" />
        <el-table-column align="center" prop="subscriber.userId" label="用户Id" width="100" />
        <el-table-column align="center" prop="subscriber.scOpenId" label="用户OpenId" width="300" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.subscriber?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.subscriber?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.subscriber?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="taskId" label="任务ID" width="200" />
        <el-table-column align="center" prop="title" label="任务标题" width="200" />
        <el-table-column align="center" prop="cycleStart" label="签到开始日期" width="200" />
        <el-table-column align="center" prop="signDays" label="连续签到天数" width="200" />
        <el-table-column align="center" prop="couponInfo.id" label="券ID" width="200" />
        <el-table-column align="center" prop="couponInfo.name" label="券名称" width="200" />
        <el-table-column align="center" prop="type" label="券类型" width="100">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.couponInfo?.type === 1 ? '赠品券'
                : scope.row.couponInfo?.type === 2 ? '奖品券'
                  : scope.row.couponInfo?.type === 3 ? '满减券' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('signintaskSentcoupon').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 120px;
    margin-right: 10px;
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
